
// 导出页面为PDF格式
import {Toast} from 'vant'
import store from '../store/store.js'
import axios from 'axios'
import {uploadFile } from "@/api/image_upload";
import html2canvas from "html2canvas"
import JSPDF from "jspdf"
//将base64转换为文件对象
function dataURLtoFile(dataurl, filename) {
  var arr = dataurl.split(',');
  var mime = arr[0].match(/:(.*?);/)[1];
  var bstr = atob(arr[1]);
  var n = bstr.length;
  var u8arr = new Uint8Array(n);
  while(n--){
      u8arr[n] = bstr.charCodeAt(n);
  }
  //转换成file对象
  return new File([u8arr], filename, {type:mime});
  //转换成成blob对象
  //return new Blob([u8arr],{type:mime});
}
//判断当前机器是移动端还是pc端
function isMobile() {
  let isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
  return isMobile;
}

export default {
  install (Vue, options) {
    Vue.prototype.ExportSavePdf = function (id, workflow_name) {
      store.state.loading = true
      var element = document.getElementById("TicketTable")
      html2canvas(element, {
        useCORS: true,
        allowTaint : false,
        taintTest : false,
      }).then(function (canvas) {
        var pdf = new JSPDF("p", "mm", "a4") // A4纸，纵向
        var ctx = canvas.getContext("2d")
        var a4w = 170; var a4h = 277 // A4大小，210mm x 297mm，四边各保留20mm的边距，显示区域170x257
        var imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度
        var renderedHeight = 0

        while (renderedHeight < canvas.height) {
          var page = document.createElement("canvas")
          page.width = canvas.width
          page.height = Math.min(imgHeight, canvas.height - renderedHeight)// 可能内容不足一页

          // 用getImageData剪裁指定区域，并画到前面创建的canvas对象中
          page.getContext("2d").putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
          pdf.addImage(page.toDataURL("image/jpeg", 1.0), "JPEG", 20, 10, a4w, Math.min(a4h, a4w * page.height / page.width)) // 添加图像到页面，保留10mm边距

          renderedHeight += imgHeight
          if (renderedHeight < canvas.height) { pdf.addPage() }// 如果后面还有内容，添加一个空页
          // delete page;
        }
        if(isMobile()){
          var buffer = pdf.output("datauristring")
          var myfile = dataURLtoFile(buffer,workflow_name + id )
          // myfile 需要的pdf文件

          let basePath = "media/print_file/"
          if (process.env.NODE_ENV === 'development') {
            basePath = "media/debug/print_file/"
          }
          let data = {
            Key: basePath + myfile.name + ".pdf",
            file: myfile,
          }
          uploadFile(data, (err, info) =>{
            if (err) {
              Toast.fail(err)
            }else{
              let params = {
                media_url:info.url
              }
              store.dispatch('api_post_ticketPdf',params).then(res=>{
                console.log(res)
                store.state.loading = false
                Toast.success("打印成功，稍后将会以工作通知的形式发送给您")
              }).catch(err=>{
                Toast.fail("打印失败，请稍后重试")
              })
            }
          })
        }else{
          store.state.loading = false
          pdf.save(workflow_name + id)
        }
      })
    }
  }
}
